import {getRequest} from "./api";

export const initMenu = (router, store) => {
    // 如果stroe(存储vuex组件状态)有，则直接return
    if (store.state.routes.length > 0) {
        return;
    }
    // 如果没有, 请求网络
    getRequest("/system/config/menu").then(data => {
        // 如果data不为空，将请求到的response放入route
        if (data) {
            let fmtRoutes = formatRoutes(data);
            router.addRoutes(fmtRoutes);
            // 提交到store
            store.commit('initRoutes', fmtRoutes);
        }
    })
};

// 格式化Routes
export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        // 递归调用
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve){
                // 拼接组件
                if (component.startsWith('Home')){
                    require(['../views/'+component+'.vue'], resolve);
                } else if (component.startsWith('Emp')){
                    require(['../views/emp/'+component+'.vue'], resolve);
                } else if (component.startsWith('Per')) {
                    require(['../views/per/'+component+'.vue'], resolve);
                } else if (component.startsWith('Sal')) {
                    require(['../views/sal/'+component+'.vue'], resolve);
                } else if (component.startsWith('Sta')) {
                    require(['../views/sta/'+component+'.vue'], resolve);
                } else if (component.startsWith('Sys')) {
                    require(['../views/sys/'+component+'.vue'], resolve);
                }
            }
        };
        fmRoutes.push(fmRouter)
    });
    return fmRoutes;
};
